package coreservlets;

import java.util.concurrent.*;

// A variation of the RaceConditionsApp. There is no IO between
// setting currentThreadNum and updating the shared latestThreadNum,
// yet still the race condition can occur. On recent Java implementations
// and fast computers, the race condition still shows up about once
// in every 50 tests.

public class RaceConditionsApp2 implements Runnable {
  private final static int LOOP_LIMIT = 5;
  private final static int POOL_SIZE = 10;
  private int latestThreadNum = 0;
  
  public RaceConditionsApp2() {
    ExecutorService taskList;
    taskList = Executors.newFixedThreadPool(POOL_SIZE);
    for (int i=0; i<POOL_SIZE; i++) {
      taskList.execute(this);
    }
  }
  
  public void run() {
	int currentThreadNum=0;
    synchronized(this){
    	currentThreadNum = latestThreadNum;
    }
    String message = "Set currentThreadNum to " + currentThreadNum;
    latestThreadNum = latestThreadNum + 1;
    System.out.println(message);
    for (int i=0; i<LOOP_LIMIT; i++) {
      doSomethingWith(currentThreadNum);
    }
  }
  
  private void doSomethingWith(int threadNumber) {
    // Blah blah
  }
}
